/*
 * 文件名：GoodsController.java
 * 版权：Copyright by hlst
 * 描述：
 * 修改人：liuziyu
 * 修改时间：2016年7月22日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.shop.controller.goods;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.constants.ShopConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.manage.model.base.CommonImg;
import com.zcsy.manage.model.mall.GoodsCategory;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.GoodsSpecAttrNameValue;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.service.mall.IGoodsCategoryService;
import com.zcsy.manage.service.mall.IGoodsInfoService;

@Controller
@RequestMapping(value = "/shopGoods")
public class GoodsController {


	@Autowired
	private IGoodsCategoryService goodsCategoryService;
	
	@Autowired
	private IGoodsInfoService goodsInfoService;
	
	  /**
     * @Method: getGoodsCategory
     * @Description 获取商品分类信息（商品两级分类）
     * @param shopId 店铺id
     * @return result 
     * @author yangfan 373188993@qq.com
     * @date 2016年7月12日
     * @see 
     */
    @RequestMapping(value = "getGoodsCategory")
    @ResponseBody
    public RequestJson getGoodsCategory(String shopId) {
        
        RequestJson result = new RequestJson();
        
        try {
            List<GoodsCategory> goodsCategory  = goodsCategoryService.selectCategoryByShopId(shopId);
            
            if(!goodsCategory.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取商品分类信息成功！");
                result.setObj(goodsCategory);
            } else {
                result.setSuccess(false);
                result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
                result.setMsg("无数据！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;
    }
    
    /**
     * @Description 获取商品信息详情
     * @param goodsId 商品id
     * @return 商品相关信息
     * @author luoyzh 823884124@qq.com
     */
    @RequestMapping(value = "getGoodsDetail")
    @ResponseBody
    public RequestJson getGoodsDetail(String goodsId) {
    	RequestJson result = new RequestJson();
    	GoodsInfo goodsInfo = new GoodsInfo();
        try {
			goodsInfo = goodsInfoService.getGoodsInfoDetail(goodsId);
			List<GoodsSpecAttrNameValue> goodsSpecAttrNameValueList  = goodsInfoService.getGoodsSpecAttrNameValueList(goodsId);
			List<String> list = goodsInfoService.getAttrNameList(goodsId);
			List<Map<String, Object>> goodsSpecList = new ArrayList<Map<String,Object>>();
			
			for (String name : list) {
				Map<String, Object> map = new HashMap<String, Object>();
				List<Map<String, Object>> attrValueList = new ArrayList<Map<String, Object>>();
				
				for (GoodsSpecAttrNameValue nameValue : goodsSpecAttrNameValueList) {
					if (nameValue.getAttrName()!=null&&nameValue.getAttrName().equals(name)) {
						Map<String, Object> mapValue = new HashMap<String, Object>();
						mapValue.put("attrValue", nameValue.getAttrValue());
						attrValueList.add(mapValue);
					}
				}
				map.put("attrValueList", attrValueList);
				map.put("attrName", name);
				goodsSpecList.add(map);
			}
			
			List<GoodsSpecification> specifiedGoodsInfo = goodsInfoService.getGoodsSpecWithValuesList(goodsId);
			List<CommonImg> commonImgList  = goodsInfoService.getGoodsImgList(goodsId);
			Map<String, Object> mapAll = new HashMap<String, Object>();
			mapAll.put("goodsSpecList", goodsSpecList);//该商品所有规格信息
			mapAll.put("goodsInfo", goodsInfo);//商品基本信息
			mapAll.put("specifiedGoodsInfo", specifiedGoodsInfo);//选好该商品各规格后的商品价格库存等信息
			mapAll.put("commonImgList", commonImgList);//商品轮播图
			mapAll.put("wapUrl", OwnerConstants.WAP_URL + "/mall/getGoodsPicText?id="+goodsId);//该商品图文详情
			if (goodsInfo != null) {
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("数据获取成功！");
				result.setObj(mapAll);
			}else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
				result.setMsg("无数据！");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.GET_USERINFO_FALSE);
			result.setMsg("网络异常");
		}
        return result;
    }
    
    /**
     * @Method: putGoodsAvailable
     * @Description 商品上下架
     * @param goodsId 商品id
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月25日
     * @see 
     */
    @RequestMapping(value = "putGoodsAvailable")
    @ResponseBody
    public RequestJson putGoodsAvailable(String goodsId) {
    	RequestJson result = new RequestJson();
    	
    	// 查询商品的状态
    	GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(goodsId);
    	if (goodsInfo != null) {
    		int oldState = goodsInfo.getState();
    		
    		// 如果商品正常，则操作为下架
    		if (oldState == ShopConstants.GOODS_STATE_NORMAL) {
    		    goodsInfo.setState(ShopConstants.GOODS_STATE_UNDERCARRIAGE);
    			int state = goodsInfoService.updateByPrimaryKey(goodsInfo);
    			if (state == ShopConstants.UPDATE_SUCCESS) {
    				result.setSuccess(true);
    				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
    				result.setMsg("商品下架成功！");
    				result.setObj(goodsInfo);
				} else {
					result.setSuccess(false);
					result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
					result.setMsg("商品下架失败！");

				}
    			
    			// 如果商品下架，操作为上架
    		}else if (oldState == ShopConstants.GOODS_STATE_UNDERCARRIAGE) {
    		    goodsInfo.setState(ShopConstants.GOODS_STATE_NORMAL);
    			int state = goodsInfoService.updateByPrimaryKey(goodsInfo);
    			if (state == ShopConstants.UPDATE_SUCCESS) {
    				result.setSuccess(true);
    				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
    				result.setMsg("商品上架成功！");
    				result.setObj(goodsInfo);
				} else {
					result.setSuccess(false);
					result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
					result.setMsg("商品上架失败！");

				}
    			
    		}else {
    			result.setSuccess(false);
    			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
    			result.setMsg("商品状态有误！");
    		}
			
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("商品id有误！");

		}
    	
    	return result;
    }
    
    /**
     * @Method: getAllGoods
     * @Description 获取店铺商品信息（二级菜单目录下）
     * @param goodsCategoryId 商品分类id
     *        shopId     店铺id
     *        state 状态（1在售，2售罄，3待售）
     *        pNo 分页
     * @return result 
     * @author liuziyu
     * @date 2016年7月26日
     * @see 
     */
    @RequestMapping(value = "getAllGoods")
    @ResponseBody
	public RequestJson getAllGoods(String goodsCategoryId, String shopId,
			Integer state, Integer pNo) {

		RequestJson result = new RequestJson();
		GoodsInfo goodsInfo = new GoodsInfo();

		// 指定默认为首页
        if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
            pNo = ShopConstants.PAGE_NO;
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, ShopConstants.PAGE_SIZE);
		
		// 1在售
		if (state == ShopConstants.GOODSSTATE_SELLING) {
			goodsInfo.setGoodsCategoryId(goodsCategoryId);
			goodsInfo.setShopId(shopId);
			goodsInfo.setState(ShopConstants.SQL_GOODSSTATE_NORMAL);
			List<GoodsInfo> goodsInfoList = goodsInfoService
					.selectShopGoodsInfoByKeyWords(goodsInfo);

			if (!goodsInfoList.isEmpty()) {
				// 分页
		        PageInfo<GoodsInfo> goodsInfoListP = new PageInfo<GoodsInfo>(goodsInfoList);
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("获取在售店铺商品成功！");
				result.setObj(goodsInfoListP);
			} else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
				result.setMsg("无数据！");
			}

			// 2售罄
		} else if (state == ShopConstants.GOODSSTATE_SELL_OUT) {
			goodsInfo.setGoodsCategoryId(goodsCategoryId);
			goodsInfo.setShopId(shopId);
			goodsInfo.setStock(ShopConstants.SQL_GOODSSTATE_SELL_OUT);
			goodsInfo.setState(-1);
			List<GoodsInfo> goodsInfoList = goodsInfoService
					.selectShopGoodsInfoByKeyWords(goodsInfo);

			if (!goodsInfoList.isEmpty()) {
				// 分页
		        PageInfo<GoodsInfo> goodsInfoListP = new PageInfo<GoodsInfo>(goodsInfoList);
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("获取店铺售罄商品成功！");
				result.setObj(goodsInfoListP);
			} else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
				result.setMsg("无数据！");
			}

			// 3待售
		} else if (state == ShopConstants.GOODSSTATE_WAIT_SELL) {
			goodsInfo.setGoodsCategoryId(goodsCategoryId);
			goodsInfo.setShopId(shopId);
			goodsInfo.setState(ShopConstants.SQL_GOODSSTATE_OUT);
			List<GoodsInfo> goodsInfoList = goodsInfoService
					.selectShopGoodsInfoByKeyWords(goodsInfo);

			if (!goodsInfoList.isEmpty()) {
				// 分页
		        PageInfo<GoodsInfo> goodsInfoListP = new PageInfo<GoodsInfo>(goodsInfoList);
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("获取店铺待售商品成功！");
				result.setObj(goodsInfoListP);
			} else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
				result.setMsg("无数据！");
			}
			
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("状态有误！");
		}
		return result;
	}
    
    /**
     * @Method: putGoodsTop
     * @Description 商品置顶
     * @param goodsId 商品id
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月27日
     * @see 
     */
    @RequestMapping(value = "putGoodsTop")
    @ResponseBody
	public RequestJson putGoodsTop(String goodsId) {

		RequestJson result = new RequestJson();
		
		// 查询此商品的一级分类
		String parentId = goodsCategoryService.selectParentIdByGoodsId(goodsId);
		
		if (parentId != "") {
			// 查询一级分类下推荐指数最高的商品
			List<GoodsInfo> topGoodsInfo = goodsInfoService.selectTopRecommendByParentId(parentId);
			Iterator<GoodsInfo> iterator = topGoodsInfo.iterator();
			int top = 0;
			// 判断此商品在一级分类下推荐指数是否已经最高
			boolean exist = false;
			while (iterator.hasNext()) {
				GoodsInfo topOneGoodsInfo = (GoodsInfo) iterator.next();
				top = topOneGoodsInfo.getIsRecommend();
				if (topOneGoodsInfo.getId().equals(goodsId)) {
					exist = true;
					break;
				}
			}
			
			// 若此商品在一级分类下推荐指数不是最高
			if (exist == false) {
				GoodsInfo newTopGoodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(goodsId);
				newTopGoodsInfo.setIsRecommend(++top);
				int state = goodsInfoService.updateByPrimaryKey(newTopGoodsInfo);
				
				if (state == ShopConstants.UPDATE_SUCCESS) {
					result.setSuccess(true);
					result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
					result.setMsg("商品置顶成功！");
					result.setObj(newTopGoodsInfo);
				} else {
					result.setSuccess(false);
					result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
					result.setMsg("商品置顶失败！");
				}
			} else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
				result.setMsg("该商品已经置顶！");
			}
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("查询不到该商品分类信息！");
		}
		return result;
	}
    
    /**
     * @Description 根据关键字搜索商品
     * @param name 商品名字（模糊查询）
     * @param pNo 页数
     * @param shopId 店铺id
     * @return 商品信息列表
     * @author yangfan 373188993@qq.com
     * @data 2016年7月27日
     */
    @RequestMapping(value = "getSearchGoodsList")
    @ResponseBody
    public RequestJson getSearchGoodsList(String name,Integer pNo,String shopId) {
        
        RequestJson result = new RequestJson();
        
        try {
            // 指定默认为首页
            if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
                pNo = OwnerConstants.PAGE_NO;
            }
            // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
            PageHelper.startPage(pNo, Constants.PAGE_SIZE);
            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setName(name);
            goodsInfo.setShopId(shopId);
            List<GoodsInfo> goodsinfoList = goodsInfoService.getShopGoodsList(goodsInfo);
            PageInfo<GoodsInfo> goodsinfoListP = new PageInfo<GoodsInfo>(goodsinfoList);
            if(!goodsinfoList.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取商品列表成功！");
                result.setObj(goodsinfoListP);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("无数据！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;
    }
}
